package org.mte.swift.support;

import static org.mte.swift.parameter.SwiftParameter.*;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.mte.swift.web.form.Message;
import org.mte.swift.web.util.UrlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

@Service("supportHandler")
public class SupportHandlerImpl implements SupportHandler {
	
	@Autowired
	protected MessageSource messageSource;
	
	public SupportHandlerImpl() {
		
	}
	
	public String prepareEntityUrl(String url, Long id, HttpServletRequest request) {
		return url + UrlUtil.encodeUrlPathSegment(id.toString(), request);
	}	
	
	public Message retrieveCreateSuccessMessage(String key, Locale locale) {
		return retrieveMessageByArgKey(CREATE_SUCCESS_MESSAGE_KEY, key, locale);
	}
	
	public Message retrieveCreateErrorMessage(String key, Locale locale) {
		return retrieveMessageByArgKey(CREATE_ERROR_MESSAGE_KEY, key, locale);
	}
	
	public Message retrieveUpdateSuccessMessage(String key, Locale locale) {
		return retrieveMessageByArgKey(UPDATE_SUCCESS_MESSAGE_KEY, key, locale);
	}
	
	public Message retrieveUpdateErrorMessage(String key, Locale locale) {
		return retrieveMessageByArgKey(UPDATE_ERROR_MESSAGE_KEY, key, locale);
	}

	public Message retrieveGenericErrorMessage(String arg) {
		//return retrieveMessage(GENERIC_ERROR_MESSAGE_KEY, arg, null);
		return new Message(Message.MESSAGE_ERROR_TYPE, arg);
	}
	
	
	public Message retrieveMessageByArgKey(String key, String argKey, Locale locale) {
		Object[] args = new Object[1];
		args[0] =  messageSource.getMessage(argKey, new Object[]{}, locale);
		return retrieveMessage(key, args, locale);
	}
	
	public Message retrieveMessage(String key, String arg, Locale locale) {
		Object[] args = new Object[1];
		args[0] = arg;
		return retrieveMessage(key, args, locale);
	}
	
	public Message retrieveMessage(String key, Object[] args, Locale locale) {
		String type = key;
		int pos = key.lastIndexOf(".");
		if (pos != -1) {
			type = type.substring(pos + 1);
		}
		return new Message(type, messageSource.getMessage(key, args, locale));
	}	
}
